<template>
    <div class="read">
        <div class="postRead">
            <div class="top">
                <h2>
                    {{ data.title }}
                </h2>
            </div>
            <div class="content" ref="content">
            </div>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios'
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/User.js'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/default.css'

const data = ref({})
const router = useRouter()
const route = useRoute()
let UserStore = useUserStore()
const content = ref(null)

marked.setOptions({
    highlight: function (code, language) {
        const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'
        return hljs.highlight(code, { language: validLanguage }).value
    }
})

onMounted(() => {
    if (UserStore.UserID === '' && UserStore.UserName === '') {
        router.push({
            path: '/auth'
        })
    } else {
        axios({
            method: 'put',
            url: `http://127.0.0.1:8000/api/post/views/${route.params.id}`
        }).then(res => {
            console.log(res)
        }).catch(err => {
            console.log(err)
        })
        axios({
            method: 'get',
            url: `http://127.0.0.1:8000/api/post/${route.params.id}`
        }).then(res => {
            data.value = res.data.data[0]
            content.value.innerHTML = marked(data.value.content)
            hljs.highlightAll()
        }).catch(err => {
            console.log(err)
        })
    }
})
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.read {
    width: 100vw;
    height: 100vh;
    background-color: rgb(242, 243, 245);
    display: flex;
    justify-content: center;
    align-items: center;
}

.postRead {
    width: 95%;
    height: 100%;
    background-color: white;
    border-radius: 5px;
    overflow-y: auto;
}

.postRead>div {
    width: 95%;
    box-sizing: border-box;
    margin: 0 auto;
}

.top {
    height: 100px;
    margin-bottom: 2%;
    border-bottom: 1px solid rgb(197, 199, 202);
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>